package com.inno.thread.thread.concurrent.utils;

import java.util.concurrent.*;

public class BankWaterService implements Runnable {
    /** 创建屏障，阻塞4个线程，处理完成之后，执行当前类的run方法 */
    private CyclicBarrier cyclicBarrier = new CyclicBarrier(4, this::run);
    /** 提交4个线程计算银行流水 */
    private Executor executor = Executors.newFixedThreadPool(4);
    /** 保存每个Sheet的银行流水计算结果 */
    private ConcurrentHashMap<String, Integer> sheetBankWater = new ConcurrentHashMap<>(4);

    @Override
    public void run() {
        int result = 0;
        for (Integer value : sheetBankWater.values()) {
            result += value;
        }
        System.out.println("result = " + result);
    }

    private void countBankWater() {
        for (int i = 0; i < 4; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    int waterInSheet = countWaterInSheet();
                    sheetBankWater.put(Thread.currentThread().getName(), waterInSheet);
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /* 计算每张Sheet银行流水 */
    public int countWaterInSheet() {
        return 1;
    }

    public static void main(String[] args) {
        BankWaterService bankWaterService = new BankWaterService();
        bankWaterService.countBankWater();
    }
}
